﻿/* File Created: 七月 21, 2013 */
var ComFunJS = new Object();
ComFunJS.isIE= function () {
    if (!!window.ActiveXObject || "ActiveXObject" in window)
        return true;
    else
        return false;
}
ComFunJS.getQueryString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
ComFunJS.getRootPath = function () {
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return (localhostPaht + projectName);
}
 
//将长度超过10的字符串用省略号代替
ComFunJS.convstr = function (str, len) {
    if (str) {
        str = str.replace(/<[^>]+>/g, "");
        if (len) {
            return str.length > len ? str.substr(0, len) + "..." : str;
        }
        else {
            return str;
        }
    }
}
//选择角色代码
ComFunJS.GetBMPeople = function (dom) {
    var checkvalue = dom.next('input:hidden').val();
    if (dom.data("people")) {
        checkvalue = dom.data("people").userid;
    }
    var strFliter = dom.attr("Action") ? "&Action=" + dom.attr("Action") : "";
    parent.MyDialog.btnwin('/View/Comon/UserListN.aspx?checkvalue=' + checkvalue + strFliter, '1000', '580', "", function (layero, index) {
        var frameid = $("iframe", $(layero)).attr('id');
        var people = parent.window.frames[frameid].getqiandaopeople();
        //var people = ComFunJS.isIE() ? top.window.frames[frameid].getqiandaopeople() : top.window.frames[frameid].contentWindow.getqiandaopeople();
        dom.data("people", people).val(people.username).next('input:hidden').val(people.userid);
        if (dom.is("td")) {
            dom.text(people.username);
        }
        parent.layer.close(index)
    })
}


ComFunJS.GetBMPeopleTree = function (tip, $valdom) {


    $.ajax({
        type: "GET",
        url: ComFunJS.getRootPath() + "/Base/AdminHandle.ashx",
        dataType: "html",
        data: { "CheckNodes": $valdom.val(), "Action": "GetBranchUser" },
        beforeSend: function (XMLHttpRequest) {
            parent.MyDialog.Mytips();
        },
        success: function (msg) {
            var zNodes = null;
            var zTreeObj = null;
            var setting = {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: { "Y": "ps", "N": "ps" }
                },
                view: {
                    showLine: false
                },
                callback: {
                    onCheck: function (event, treeId, treeNode) {
                        var checknodes = zTreeObj.getCheckedNodes(true);
                        var s = "";
                        if (checknodes.length != 0) {
                            $.each(checknodes, function (i, n) {
                                var check = (n && n.isUser == "Y");
                                if (check) {
                                    s = s + n.id + ',';
                                }
                            });
                            $valdom.val(s);
                        }
                    }
                }
            };
            zNodes = eval(msg);
            zTreeObj = $.fn.zTree.init($(".ztree", tip), setting, zNodes);
        },
        complete: function (XMLHttpRequest, textStatus) {
            parent.MyDialog.CloseMytips();
        },
        error: function () {
        }
    });

}

ComFunJS.initForm = function () {

    //时间
    //日期

    if ($(".form_date")[0]) {
        $(".form_date").datetimepicker({
            format: "yyyy-mm-dd"
        });
        $(".form_date").each(function () {
            if ($(this).val() === "" && !$(this).hasClass("null")) {
                $(this).val(ComFunJS.getnowdate("yyyy-mm-dd"));
            }


            $(this).trigger('change')
        })
    }


    //年份
    if ($(".form_date_year")[0]) {
        $(".form_date_year").datetimepicker({
            minView: 4,
            startView: 4,
            format: "yyyy"
        })
        if ($(".form_date_year").val() === "") { $(".form_date_year").val(ComFunJS.getnowdate("yyyy")); }
        $(".form_date_year").trigger('change')
    }

    //月份
    if ($(".form_date_mon")[0]) {
        $(".form_date_mon").datetimepicker({
            minView: 3,
            startView: 3,
            format: "yyyy-mm"
        })
        if ($(".form_date_mon").val() === "") { $(".form_date_mon").val(ComFunJS.getnowdate("yyyy-mm")); }
        $(".form_date_mon").trigger('change')
    }

    //时间
    if ($(".form_date_time")[0]) {
        $(".form_date_time").datetimepicker({
            minView: 0,
            format: "yyyy-mm-dd hh:ii"
        });
    }
    if ($(".Yan_Date")[0]) {
        $(".Yan_Date").each(function () {
            $(this).text(ComFunJS.converdate($.trim($(this).text())))
        })
    }

    //转换中文名称
    if ($(".YanUserRealName")[0]) {
        $(".YanUserRealName").each(function () {
            $(this).text(ComFunJS.convertuser($.trim($(this).text())))
        })
    }
    if ($(".YanBranchName")[0]) {
        $(".YanBranchName").each(function () {
            $(this).text(ComFunJS.convertbranch($.trim($(this).text())))
        })
    }
    //$('.getPeoples').bind('click', function () { ComFunJS.GetBMPeople($(this)) }).attr("onfocus", "this.blur()");
    $(".getPeoples:hidden").each(function () {
        var $input = $(this);
        $input.attr("isinit", "Y");//是否已初始化
        var issignle = $(this).attr("signle") ? "Y" : "N";
        var panval = "";
        if ($input.val() != "") {
            $.each($input.val().split(','), function (i, n) {
                if (ComFunJS.convertuser(n)) {
                    panval = panval + '<span class="label label-info" style="display: inline-block;margin-right: 10px;padding: 3px;margin-top: 3px;">' + ComFunJS.convertuser(n) + '<span class="badge peopledel" style="background-color: brown;font-size: x-small;" nowuser="' + n + '">X</span></span>';
                }
            });
        }
        //先删除之前的东西
        $input.parent().find(".panpel").remove()
        var $panelsc = $('<div class="panel panel-default panpel" style="margin-bottom: 0px;"><div class="panel-body" style="padding: 6px;max-height:100px;overflow:auto">' + panval + '<a href="javascript:void(0)"  class="btn-upload">选择人员</a><i class="iconfont icon-838ribao" style="display:none"></i></div></div>');

        $(".peopledel", $panelsc).one('click', function () {//绑定删除人员事件
            var nowuser = $(this).attr("nowuser");
            $(this).parent().remove();//删除dom标签
            var people = ("," + $input.val() + ",").replace(nowuser + ",", "");
            if (people.substring(0, 1) == ",") {
                people = people.substring(1);
            }
            if (people.substring(people.length - 1, people.length) == ",") {
                people = people.substring(0, people.length - 1);
            }
            $input.val(people);
        });
        $panelsc.insertAfter($input);
        $panelsc.find('.btn-upload').bind('click', function () {
            var $btnSel = $(this);
            var peopleType = "";//选择人范围类型
            if ($input.attr("usertype")) {
                peopleType = "&userType=" + $input.attr("usertype") + "&typeid=" + $input.attr("typeid");
            }
            top.MyDialog.btnwin("/View/Comon/UserListN.aspx?checkvalue=" + $input.val() + "&issignle=" + issignle + peopleType, "1000", "600","", function (layero, index) {
                var frameid = $("iframe", $(layero)).attr('id');
                var people = parent.window.frames[frameid].getqiandaopeople();
                //var people = ComFunJS.isIE() ? top.window.frames[frameid].getqiandaopeople() : top.window.frames[frameid].contentWindow.getqiandaopeople();

                $input.data("people", people).val(people.userid);
                $btnSel.parent().find(".label-info").remove();
                $.each(people.username.split(','), function (i, n) {
                    if (n != "") {
                        var $peo = $('<span class="label label-info" style="display: inline-block;margin-right: 10px;padding: 3px; margin-top: 3px;">' + n + '<span class="badge peopledel" style="background-color: brown;font-size: x-small;" nowuser="' + people.userid.split(',')[i] + '">X</span></span>');
                        $peo.insertBefore($btnSel)
                    }
                });
                $(".peopledel", $panelsc).one('click', function () {//绑定删除人员事件
                    var nowuser = $(this).attr("nowuser");
                    $(this).parent().remove();//删除dom标签
                    var people = ("," + $input.val() + ",").replace(nowuser + ",", "");
                    if (people.substring(0, 1) == ",") {
                        people = people.substring(1);
                    }
                    if (people.substring(people.length - 1, people.length) == ",") {
                        people = people.substring(0, people.length - 1);
                    }
                    $input.val(people);
                });
                top.layer.close(index)
            })
        })

    })

    //提示插件
    try {
        //表单验证
        $("Form").validationEngine("attach", {
            autoPositionUpdate: true,
            scroll: false,
            validateNonVisibleFields: false,
            prettySelect: true,
            showOneMessage: true
        });
        //表单验证
    } catch (e) {

    }
    if ($(".UEEDIT").length > 0) {
        $(".UEEDIT").each(function () {
            var ubid = $(this).attr("id");
            var input = $(this);
            var um = UM.getEditor(ubid);
            if ($(this).attr("umheight")) {
                um.setHeight($(this).attr("umheight"));
            } else {
                um.setHeight("300")
            }
            if (input.val() != "") {
                um.ready(function () {
                    //需要ready后执行，否则可能报错
                    um.setContent(input.val());
                })
            }

            um.addListener('contentChange', function () {
                input.val(UM.getEditor(ubid).getContent())
            })
            if ($(this).hasClass("focus")) {
                um.ready(function () { um.focus() })
            }
        })
    }

    if ($(".FT_Upload:hidden").length > 0) {
        $(".FT_Upload:hidden").each(function () {
            var $input = $(this);
            //var btnName = $(this).attr('title') ? $(this).attr('title') : "上传文件";//按钮名称
            var btnName = $(this).attr('title') ? $(this).attr('title') : "上传文件";//按钮名称
            var FileType = $(this).attr('FileType') ? $(this).attr('FileType') : "";//文件类型(pic代表图片)
            var $panelsc = $('<div class="panel panel-default"><div class="panel-body"><input type="button" value="' + btnName + '" class="btn btn-info btn-upload" /></div><ul class="list-group"></ul></div>')
                .insertAfter($input);
            $panelsc.find('.btn-upload').bind('click', function () {
                parent.MyDialog.btnwin('/View/Comon/UploadFile.html?FileType=' + FileType, '500', '395', {}, function (layero, index) {
                    var frameid = $("iframe", $(layero)).attr('id');
                    //var nowwin= ComFunJS.isIE() ? top.window.frames[frameid] : top.window.frames[frameid].contentWindow;
                    var nowwin =top.window.frames[frameid] ;
                    var fjdata = nowwin.getfjdata();
                    var fjids = "";
                    for (var i = 0; i < fjdata.length; i++) {
                        var showText = "";
                        if (fjdata[i].FileType == "pic") {
                            showText = "<image src='/" + fjdata[i].FileUrl + "' class='img-rounded btn-upload' style='width:100px;height:100px' />";
                        } else {
                            showText = fjdata[i].FileOldName;
                        } 
                        var $fileitem = $("<a    class='list-group-item'   fileid='" + fjdata[i].ID + "' >" + showText + "<span class='glyphicon glyphicon-download-alt'  fileid='" + fjdata[i].ID + "' style='margin-left: 5px;'></span><span class='glyphicon glyphicon-trash pull-right'></span></a>");
                        $fileitem.find('.glyphicon-trash').bind('click', function () {
                            $(this).parent().remove();
                            var tempfjids = "";
                            $panelsc.find('.list-group-item').each(function () {
                                tempfjids = tempfjids + $(this).attr("fileid") + ",";
                            })
                            if (tempfjids.length > 0) {
                                tempfjids = tempfjids.substring(0, tempfjids.length - 1)
                            }
                            $input.val(tempfjids);
                        })
                        $fileitem.find('.glyphicon-download-alt').bind('click', function () {
                            window.open(ComFunJS.getRootPath() + "/Comon/DownLoadFile.aspx?FileID=" + $(this).attr("fileid"));
                        })

                        $panelsc.find('.list-group').append($fileitem);
                    }

                    $panelsc.find('.list-group-item').each(function () {
                        fjids = fjids + $(this).attr("fileid") + ",";
                    })
                    if (fjids.length > 0) {
                        fjids = fjids.substring(0, fjids.length - 1)
                    }
                    $input.val(fjids);
                    parent.layer.close(index)

                });
            })
            if ($input.val() != "") {
                $.getJSON(ComFunJS.getRootPath() + "/Comon/ComAjaxHandler.ashx", { Action: "GetFiles", FileIDS: $input.val() }, function (data) {
                    if (data) {
                        var fjdata = data;
                        for (var i = 0; i < fjdata.length; i++) {
                            var showText = "";
                            if (fjdata[i].FileType == "pic") {
                                showText = "<image src='/" + fjdata[i].FileUrl + "' class='img-rounded btn-upload' style='width:100px;height:100px' />";
                            } else {
                                showText = fjdata[i].FileOldName;
                            }
                            var $fileitem = $("<a  class='list-group-item'    fileid='" + fjdata[i].ID + "' >" + showText + "<span class='glyphicon glyphicon-download-alt' fileid='" + fjdata[i].ID + "' style='margin-left: 5px;'></span><span class='glyphicon glyphicon-trash pull-right'></span></a>");
                            $fileitem.find('.glyphicon-trash').bind('click', function () {
                                $(this).parent().remove();
                                var tempfjids = "";
                                $panelsc.find('.list-group-item').each(function () {
                                    tempfjids = tempfjids + $(this).attr("fileid") + ",";
                                })
                                if (tempfjids.length > 0) {
                                    tempfjids = tempfjids.substring(0, tempfjids.length - 1)
                                }
                                $input.val(tempfjids);
                            })
                            $fileitem.find('.glyphicon-download-alt').bind('click', function () {
                                window.open(ComFunJS.getRootPath() + "/Comon/DownLoadFile.aspx?FileID=" + $(this).attr("fileid"));
                            })
                            $panelsc.find('.list-group').append($fileitem);
                        }
                        if ($input.attr("UploadType") == "1") {
                            $panelsc.find('.glyphicon-trash').remove();
                        }
                    }
                    else {
                        $panelsc.find('.panel-body').text("无附件");
                    }
                });
            }else
            if ($input.attr("UploadType") == "1") {
                $panelsc.find('.panel-body').text("无附件");
            }

        })
    }

}
//初始化插件
ComFunJS.getnowdate = function (format) {
    var now = new Date();

    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
    var clock = year + "-";

    if (format == "yyyy-mm") {
        if (month < 10)
            clock += "0";
        clock += month + "-";
    }

    if (format == "yyyy-mm-dd") {
        if (month < 10)
            clock += "0";
        clock += month + "-";
        if (day < 10) {
            clock += "0";
        }
        clock += day + "-";
    }
    return (clock.substr(0, clock.length - 1));

}
ComFunJS.converdate = function (date) {

    var daycount = ComFunJS.daysBetween(ComFunJS.getnowdate('yyyy-mm-dd'), date);
    var datereturn = date;
    if (daycount == -1) {
        datereturn = date + "(昨天)";
    }
    if (daycount == 0) {
        datereturn = date + "(今天)";
    }
    if (daycount == 1) {
        datereturn = date + "(明天)";
    }
    if (daycount == 2) {
        datereturn = date + "(后天)";
    }
    return datereturn;
}

ComFunJS.format = function (date, str) {
    str = str.replace(/yyyy|YYYY/, date.getFullYear());
    str = str.replace(/MM/, date.getMonth() >= 9 ? ((date.getMonth() + 1) * 1).toString() : '0' + (date.getMonth() + 1) * 1);
    str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
    return str;
}
ComFunJS.daysBetween = function (start, end) {
    var OneMonth = start.substring(5, start.lastIndexOf('-'));
    var OneDay = start.substring(start.length, start.lastIndexOf('-') + 1);
    var OneYear = start.substring(0, start.indexOf('-'));
    var TwoMonth = end.substring(5, end.lastIndexOf('-'));
    var TwoDay = end.substring(end.length, end.lastIndexOf('-') + 1);
    var TwoYear = end.substring(0, end.indexOf('-'));
    var cha = ((Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear) - Date.parse(OneMonth + '/' + OneDay + '/' + OneYear)) / 86400000);
    return cha;
},
            //日期计算
ComFunJS.DateAdd = function (date, strInterval, Number) {
    var dtTmp = date;
    switch (strInterval) {
        case 's': return new Date(Date.parse(dtTmp) + (1000 * Number));

        case 'n': return new Date(Date.parse(dtTmp) + (60000 * Number));

        case 'h': return new Date(Date.parse(dtTmp) + (3600000 * Number));

        case 'd': return new Date(Date.parse(dtTmp) + (86400000 * Number));

        case 'w': return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));

        case 'q': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());

        case 'm': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());

        case 'y': return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
    return date;
},

ComFunJS.StringToDate = function (DateStr) {
    var converted = Date.parse(DateStr);
    var myDate = new Date(converted);
    if (isNaN(myDate)) {
        //var delimCahar = DateStr.indexOf('/')!=-1?'/':'-';
        var arys = DateStr.split('-');
        myDate = new Date(arys[0], --arys[1], arys[2]);
    }
    return myDate;
},

ComFunJS.isconuser = function (userrealname) {
    var isConUser = false;
    for (var el in parent.usersarr) {
        if (parent.usersarr[el] === userrealname) {
            isConUser = true;
            break;
        }
    }
    return isConUser;
}
ComFunJS.convertuser = function (user) {
    var returnmsg = "";
    var arruser = user.split(",");
    if (user !== "") {
        var bl = false;
        if ($("body").data("usersarr")) {
            var usersarr = $("body").data("usersarr");
            for (var i = 0; i < arruser.length; i++) {
                if (usersarr[$.trim(arruser[i])] != undefined) {
                    returnmsg = returnmsg + "," + usersarr[$.trim(arruser[i])];
                }
                else {
                    bl = true;
                    break;
                }
            }
        } else {
            bl = true;
        }
        if (bl) {
            returnmsg = '';
            var usersarr = ComFunJS.getuserdata();
            for (var i = 0; i < arruser.length; i++) {
                if (usersarr[arruser[i]] != undefined) {
                    returnmsg = returnmsg + "," + usersarr[arruser[i]];
                }
            }
            $("body").data("usersarr", usersarr);
        }
    }
    if (returnmsg.length > 1) {
        returnmsg = returnmsg.substring(1);
    }
    return returnmsg;
}
ComFunJS.getuserdata = function () {
    var usersarr;
    $.ajax({
        type: "GET",
        async: false,
        url: ComFunJS.getRootPath() + "/Comon/ComAjaxHandler.ashx",
        dataType: "html",
        data: { "Action": "GetUserJson" },
        success: function (msg) {
            usersarr = eval('(' + msg + ')');
        }
    });
    return usersarr;
}
ComFunJS.convertbranch = function (branch) {
    var returnmsg = branch;
    if ($("body").data("brancharr")) {
        var brancharr = $("body").data("brancharr");
        returnmsg = brancharr[branch];
    } else {
        $.ajax({
            type: "GET",
            async: false,
            url: ComFunJS.getRootPath() + "/Comon/ComAjaxHandler.ashx",
            dataType: "html",
            data: { "Action": "GetBranchJson" },
            success: function (msg) {
                brancharr = eval('(' + msg + ')');
                returnmsg = brancharr[branch];
                $("body").data("brancharr", brancharr);
            }
        });
    }
    return returnmsg;
}
ComFunJS.getsjs = function () {
    var returnnum = 0;
    var count = 1000;
    var original = new Array;//原始数组
    //给原始数组original赋值
    for (var i = 0; i < count; i++) {
        original[i] = i + 1;
    }
    for (var num, i = 0; i < count; i++) {
        do {
            num = Math.floor(Math.random() * count);
            returnnum = original[num];
        } while (original[num] == null);
        original[num] = null;
    }
    return returnnum;
}
ComFunJS.hbtable = function (table, conindex) {
    var j = 0;
    var firstdata = "";
    $("tbody tr", table).each(function (i) {
        var data = $.trim($(this).children().eq(conindex).text());
        if (i != 0) {
            if ((data != "" && data != firstdata) || i == $("tbody tr", table).length - 1) {
                var td = $("tbody tr", table).eq(i - j).children().eq(conindex)
                if (i == $("tbody tr", table).length - 1) {
                    $(this).children().eq(conindex).css("display", "none");
                    td.attr("rowspan", j + 1);
                } else {
                    td.attr("rowspan", j);
                    j = 1;
                    firstdata = data;
                }
                td.css({ "text-align": "center", "vertical-align": "middle" });
            } else {
                j++;
                $(this).children().eq(conindex).css("display", "none");

            }
        } else {
            j++;
            firstdata = data;
        }
    })
}

ComFunJS.ShowDialg = function (title, url) {
    $.layer({
        type: 2,
        title: title,
        maxmin: true,
        shadeClose: true, //开启点击遮罩关闭层
        area: ['800px', '460px'],
        offset: ['100px', ''],
        iframe: { src: url }
    });
}


ComFunJS.DelItem = function (items, delkey, delval) {
    for (var i = 0; i < items.length; i++) {
        if (items[i][delkey] == delval) {
            items.splice(i, 1);
        }
    }
}
//调用选择界面
ComFunJS.SelData = function (dom, formcode, checkvalue) {
    //var title = "选择数据";
    //top.MyDialog.viewform('/View/Comon/CommonListN.aspx?FormCode=' + formcode + '&ListType=SELECT&checkvalue=' + checkvalue, title, function () {
    //    var selids = this.content.getselids();
    //    var selrowdata = this.content.getseldata();
    //    dom.val(selids).data(selrowdata)
    //}, 820, 630, frameElement.api);

    parent.MyDialog.btnwin('/View/Comon/CommonListN.aspx?FormCode=' + formcode + '&ListType=SELECT&checkvalue=' + checkvalue, '1000', '580', "", function (layero, index) {
        var frameid = $("iframe", $(layero)).attr('id');
        var selids = parent.window.frames[frameid].getselids();
        var selrowdata = parent.window.frames[frameid].getseldata();
        dom.val(selids).data(selrowdata)
        parent.layer.close(index)
    })

}

$(function () {

    $(".resetdate").click(function () {
        $(".form_date").val("");
    });
})